package com.shuyun.ccms.encrypt.data.task;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shuyun.ccms.encrypt.common.EncryptCustomerInfo;


public class WriteCustomerPhoneTask implements Runnable {
	private Logger logger = LoggerFactory.getLogger(WriteCustomerPhoneTask.class);
	private BlockingQueue<Map<String,String>> queue;

	private CountDownLatch latch;

	public WriteCustomerPhoneTask(BlockingQueue<Map<String,String>> queue,CountDownLatch latch){
		this.queue = queue;
		this.latch = latch;
	}

	@Override
	public void run() {
		Map<String,String> map = queue.poll();
		String fileName = null;
		FileInputStream inputStream = null;
		BufferedReader br = null;
		BufferedWriter bw = null;
		String targetFileName = null;
		long start = System.currentTimeMillis();
		logger.info(" 线程："+Thread.currentThread().getName() + " 加载客户手机号码数据开始." );
		try {
			if(map == null){
				return;
			}
			fileName = map.get("fileName");
			targetFileName = map.get("targetFile");

			File targetFile = new File(targetFileName);
			if(!targetFile.getParentFile().exists()){
				targetFile.getParentFile().mkdirs();
			}
			//System.out.println("=================" + targetFile.getName() );
			if(!targetFile.exists()){
				targetFile.createNewFile();
			//	System.out.println(targetFile.getAbsolutePath() + " create success");
			}
		    inputStream = new FileInputStream(fileName);
		    br = new BufferedReader(new InputStreamReader(inputStream));
		    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile)));
		    String line = br.readLine();
		    while (!StringUtils.isEmpty(line)) {
	        	String[] datas = line.split(",");
	        	String encryptLine = null;
	        	encryptLine = EncryptCustomerInfo.encryptCustomerPhone(datas);
	           	if(encryptLine == null){
	        		continue;
	        	}
	        	bw.write(encryptLine);
		        line = br.readLine();
		    }
		    bw.flush();
		    long termal = System.currentTimeMillis();
			logger.info(" 线程："+Thread.currentThread().getName() + " 加载客户手机号码数据写入文件结束,耗时:" +(termal-start)/1000 + "s");
		}catch(Exception e){
			logger.error("加载客户手机号码数据失败. error: " + e.getMessage());
			throw new RuntimeException("加载客户手机号码数据失败"+e.getMessage());
		}finally {
		    latch.countDown();
		    if (br != null) {
		        try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		    }
		    if(bw != null){
		    	try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		    }
		}
	}
}
